package com.dlc.felear.xiaoensale.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.DeviceStatusView;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.factory.OrderFactory;
import com.dlc.felear.xiaoensale.helper.SerialManager;

/**
 * 蜂鸣器处理类
 */
public class BzzControlUtil implements Handler.Callback {
    private static final String TAG = "BzzControlUtil";
    private static BzzControlUtil instance;
    public static int ALARMTIME=Constant.BZZ_DELAY;
    private static final int HANDLERW1 = 1240;
    private boolean isAble = true;
    private final int addr = 2;
    private Handler handler;

    private BzzControlUtil() {
        handler = new Handler(this);
    }

    public static BzzControlUtil getInstance() {
        if (instance == null) {
            synchronized (BzzControlUtil.class) {
                if (instance == null) {
                    instance = new BzzControlUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 打开蜂鸣器
     */
    public void openBzz() {
        if (!isAble) {
            return;
        }
        sengHandlerMsg();
        DlcSerialPortClient.getInstance().send(SerialManager.getControlWeightSerialPort(), OrderFactory.openBzz(addr));
    }
    public void openBzz(int delayTime) {
        if (!isAble) {
            return;
        }
        sengHandlerMsg(delayTime);
        DlcSerialPortClient.getInstance().send(SerialManager.getControlWeightSerialPort(), OrderFactory.openBzz(addr));
    }

    /**
     * 关闭蜂鸣器
     */
    public void closeBzz() {
        if (!isAble) {
            return;
        }
        DlcSerialPortClient.getInstance().send(SerialManager.getControlWeightSerialPort(), OrderFactory.closeBzz(addr));
    }

    private void sengHandlerMsg(int delayTime) {
        handler.removeMessages(HANDLERW1);
        //延迟关闭蜂鸣器10秒
        handler.sendEmptyMessageDelayed(HANDLERW1,delayTime);
    }
    private void sengHandlerMsg() {
        handler.removeMessages(HANDLERW1);
        //延迟关闭蜂鸣器ALARMTIME秒
        handler.sendEmptyMessageDelayed(HANDLERW1,ALARMTIME);
    }
    public void setAlarmTime(int time){
        Log.e(TAG,"time="+time);
        if(time<=3000){
            time=3000;
        }
        ALARMTIME= time;
        DeviceStatusView.ALARMTIME=time;
    }

    /**
     * 设置地址
     */
    public void setBzzAddr() {
        if (!isAble) {
            return;
        }
        DlcSerialPortClient.getInstance().send(SerialManager.getControlWeightSerialPort(), OrderFactory.setBzzAddr(addr));
    }


    @Override
    public boolean handleMessage(Message msg) {
        if (HANDLERW1 == msg.what) {
            closeBzz();
        }
        return false;
    }
}
